package com.lcy.chatting;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ChattingActivity extends Activity {
	 private final static String IP = "10.0.2.2";
	 private final static int PORT = 10001;
	 private final static String LOGIN_ID="AndroidClient";
	 
	 private TextView lblReceive;
	 private String txtReceive;
	 private Socket socket;
	 private InputStream in;
	 private OutputStream out;
	 private final Handler handler = new Handler();
	 
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        
	        RelativeLayout layout = new RelativeLayout(this);
	        layout.setBackgroundColor(Color.rgb(255, 255, 255));
	        setContentView(layout);
	        // -- label for messages
	        lblReceive = new TextView(this);
	        lblReceive.setId(1);
	        lblReceive.setText("");
	        lblReceive.setTextSize(16.0f);
	        lblReceive.setTextColor(Color.rgb(0,0,0));
	        RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(320,400);
	        lblReceive.setLayoutParams(param1);
	        layout.addView(lblReceive);
	        // -- Thread for Connection
	        Thread cThread = new Thread(){public void run(){
	         try{
	          connect(IP,PORT);
	         } catch(Exception e){} }
	        };
	        cThread.start();
	    }
	    private void connect(String ip, int port){
	     int size;
	     byte[] w = new byte[10240];
	     txtReceive="";
	     try{
	      socket = new Socket(ip,port);
	      if(socket != null) {
	       in = socket.getInputStream();
	       out = socket.getOutputStream();
	       PrintWriter pw = new PrintWriter( new OutputStreamWriter( out ) );
	       pw.println(LOGIN_ID);
	       pw.flush() ;
	       
	       while(socket != null && socket.isConnected()){
	        size = in.read(w);
	        if(size<=0)continue;
	        txtReceive = new String(w,0,size,"UTF-8");
	        handler.post(new Runnable(){
	         public void run() {
	          lblReceive.setText( lblReceive.getText()+txtReceive );
	         }
	        });
	       }
	      }
	     } catch (Exception ex) {Log.e("socket",ex.toString());}
	    }
}